from django.contrib.auth import login
from django.shortcuts import render
from django.http import JsonResponse,HttpResponseRedirect
from django.views import View
# Create your views here.
from utils.customEncryption import jiami


class QQAuthURLView(View):
    """生成QQ登录的跳转链接"""
    def get(self,request):
        from QQLoginTool.QQtool import OAuthQQ
        from meiduo import settings
        #1 初始化OAuthQQ对象
        qq=OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state='huangwei' #这个随便填
        )
        #2 获取QQ登录扫码页面，扫码后得到Authorization Code
        qq_url=qq.get_qq_url()
        #3 返回json给前端
        return JsonResponse({'code':0,'errmsg':'ok','login_url':qq_url})

class QQAuthUserView(View):
    def get(self,request):
        #获取openid,并且登录
        # 1.拿到qq的code
        code=request.GET.get('code')
        # 2.通过code拿token
        from meiduo import settings
        from QQLoginTool.QQtool import OAuthQQ
        qq=OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state='huangwei' #这个随便填
        )
        token=qq.get_access_token(code)
        # 3.通过token拿openid
        openid=qq.get_open_id(token)
        # 4.判断openid是否存在
        from apps.oauth import models
        try:
            qq_uer=models.OAuthQQUser.objects.get(openid=openid)
        except Exception:
            # 5.不存在就将openid与账号绑定
            # openid加密
            from utils import customEncryption
            openid = customEncryption.encryption(openid)
            return JsonResponse({'code':400,'access_token':openid})
        else:
            # 6.存在就登录
            login(request,qq_uer.user)
            # response=HttpResponseRedirect('http://www.meiduo.site:8080/')
            response=JsonResponse({'code':0,'errmsg':'ok'})
            response.set_cookie('username',qq_uer.user.username)
            # 设置用户id（加密）
            response.set_cookie('key', jiami(expires_in=60 * 60 * 12 * 14).encryption(qq_uer.user.id))
            # 合并购物车
            from apps.carts.carts_utils import merge_cart_cookie_to_redis
            response = merge_cart_cookie_to_redis(request=request, user=qq_uer.user, response=response)

            return response

    def post(self,request):
        #openid未与阿伟小店账号绑定，进行绑定
        # 1.拿到前端的数据，校验
        # password: 密码
        # mobile: 手机
        # sms_code: 短信验证码
        # access_token: QQ的openid
        import json
        data=json.loads(request.body.decode())
        password=data.get('password')
        mobile=data.get('mobile')
        sms_code=data.get('sms_code')
        access_token=data.get('access_token')
        #openid解密
        from utils import customEncryption
        try:
            access_token=customEncryption.decrypt(access_token)
        except Exception:
            return JsonResponse({'code':400,'errmsg':'参数过期'})
        if not all([password,mobile,sms_code,access_token]): #判断参数是否完整
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        import re
        if not re.match(r'^1[3-9]\d{9}',mobile): #判断手机号
            return JsonResponse({'code':400,'errmsg':'手机号格式错误'})

        from django_redis import get_redis_connection
        redis_cli=get_redis_connection('imageCode')
        my_code=redis_cli.get(mobile)
        if my_code is None:#判断短信验证码是否过期
            return JsonResponse({'code': 400, 'errmsg': '短信验证码已过期'})

        if my_code.decode()!=sms_code:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码错误'})
        # 2.判断用户手机号是否注册
        from apps.oauth import models as o_models
        from apps.users import models as u_models
        try:
            user=u_models.User.objects.get(mobile=mobile)
        except Exception :
            # 3.没有注册，创建用户信息，进行绑定，进行状态保持
            user=u_models.User.objects.create_user(username=mobile,password=password,mobile=mobile)
            o_models.OAuthQQUser.objects.create(user=user, openid=access_token)  # openid与用户绑定
        else:
            # 4.注册了就判断用户密码，将用户信息与账号绑定，进行状态保持
            if not user.check_password(raw_password=password): #判断密码是否正确
                return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})
        #状态保持
        login(request,user)
        response=JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username',user.username)
        # 设置用户id（加密）
        response.set_cookie('key', jiami(expires_in=60 * 60 * 12 * 14).encryption(user.id))

        # 合并购物车
        from apps.carts.carts_utils import merge_cart_cookie_to_redis
        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
        # 5.返回数据给前端
        return response
